import {messages} from "share/common";
/**
 * Created by Allen on 2018/1/5.
 */
import React from 'react'
import { connect } from 'react-redux'
import httpFetch from 'share/httpFetch'
import config from 'config'

import { Table, Button, Badge } from 'antd'
import SearchArea from 'components/search-area'
import SlideFrame from 'components/slide-frame'
import NewApplicationType from 'containers/finance-setting/application-type-management/new-application-type'

class ApplicationTypeManagement extends React.Component{
  constructor(props){
    super(props);

    this.state = {
      loading: false,
      isNew: true,
      searchForm: [
        {type: 'select', id: 'setOfBooksId', label: messages('finance-setting.key52'/*账套*/), options: [],
          getUrl:`${config.baseUrl}/api/setOfBooks/by/tenant`, method: 'get', labelKey: 'setOfBooksCode', valueKey: 'id',
          getParams: {roleType: 'TENANT'}, defaultValue:''},  //账套
        {type: 'input', id: 'applicationTypeCode', label: messages('finance-setting.key53'/*申请类型代码*/)}, //申请类型代码
        {type: 'input', id: 'applicationTypeName', label: messages('finance-setting.key54'/*申请类型名称*/)}  //申请类型名称
      ],
      data: [],
      page: 0,
      pageSize: 10,
      columns:[
        {title: messages('finance-setting.key55'/*图标*/), dateIndex: 'applicationTypeIcon', width:'10%', key: 'applicationTypeIcon'},  //图标
        {title: messages('finance-setting.key53'/*申请类型代码*/), dateIndex: 'applicationTypeCode', width: '15%', key: 'applicationTypeCode'}, //申请类型代码
        {title: messages('finance-setting.key54'/*申请类型名称*/), dateIndex: 'applicationTypeName', width: '15%', key: 'applicationTypeName'}, //申请类型名称
        {title: messages('finance-setting.key52'/*账套*/), dateIndex: 'setOfBooksId', width: '10%', key: 'setOfBooksId'}, //账套
        {title: messages('finance-setting.key56'/*补贴类型*/), dateIndex: 'subsidyType', width: '15%', key:'subsidyType'}, //补贴类型
        {title: messages('common.remark'), dateIndex: 'remark', width: '15%', key: 'remark'}, //备注
        {title: messages('common.column.status'), dateIndex: 'enabled', width: '10%', key: 'enabled', render: enabled => (
          <Badge status={enabled ? 'success' : 'error'}
                 text={ enabled ? messages('common.enabled') : messages('common.status.error')}/>)
        }, //状态
        {title: messages('common.operation'), dateIndex: 'operation', width: '10%', key: 'operation', render: (text, record) => (
          <span>
            <a href="#" onClick={(e) => this.editItem(e, record)}>{messages('common.edit')}</a>
          </span>)
        }, //操作
      ],
      pagination: {
        total: 0
      },
      searchParams:{
        setOfBooksId:'',
        applicationTypeCode:'',
        applicationTypeName:''
      },
      nowApplicationType:{},
      slideFrameTitle: '',
      showSlideFrame: false,
      setOfBookOptions: []
    }
  }

  //在组件完全挂载到网页上时获取列表数据
  componentWillMount(){
    this.getList();
    const { company } = this.props;
    let searchForm = this.state.searchForm;
    let searchParams = this.state.searchParams;
    searchForm[0].defaultValue = company.setOfBooksName;
    searchParams.setOfBookId = company.setOfBooksId;
  };

//得到列表数据
  getList(){
    let params = this.state.searchParams;
    let url = `${config.baseUrl}/api/periodset?&page=${this.state.page}&size=${this.state.pageSize}`;
    for(let paramsName in params){
      url += params[paramsName] ? `&${paramsName}=${params[paramsName]}` : '';
    }
    return httpFetch.get(url).then((resp => {
      console.log(resp);
      resp.data.map((item) => {
        item.key = item.id;
      });
      this.setState({
        loading: false,
        data: resp.data,
        pagination: {
          total: Number(resp.headers['x-total-count']),
          onChange: this.onChangePager,
          current: this.state.page + 1
        }
      })
    }));
  };

  //点击分页
  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({
        page: page - 1,
        loading: true
      }, () => {
        this.getList()
      })
  };

  //搜索
  search = (result) => {
    let searchParams = {
      applicationTypeCode: result.applicationTypeCode,
      applicationTypeName: result.applicationTypeName
    };
    this.setState({
      searchParams: searchParams,
      loading: true,
      page: 0,
      pagination: {
        current: 1
      }
    }, () => {
      this.getList()
    })
  };

  reset = () => {
    this.setState({
      searchParams: {
        applicationTypeCode: '',
        applicationTypeName: ''
      }
    })
  };

  handleNew = () => {
    this.setState({showSlideFrame: true, isNew: true, nowApplicationType: {}})
  };
  handleRowClick = (record) => {
    this.setState({showSlideFrame: true, isNew: false, nowApplicationType: record })
  };

  //编辑
  editItem = (e, record) => {
    this.setState({
      showSlideFrame: true,
      isNew: false,
    })
  };

  handleCloseSlide = (success) => {
    success && this.getList();
    this.setState({ showSlideFrame : false})
  };

  render(){

    const { loading, searchForm, data, columns, isNew, pagination, showSlideFrame, searchParams, nowApplicationType} = this.state;
    return (
      <div>
        <h3 className="header-title">{messages('finance-setting.key57'/*申请类型管理*/)}</h3>
        <SearchArea
          searchForm={searchForm}
          submitHandle={this.search}
          clearHandle={this.reset}
          clearText={messages('common.reset')}/>

        <div className="table-header">
          <div className="table-header-title">{messages('common.total', {total:pagination.total})}</div>{/*共total条数据*/}
          <div className="table-header-buttons">
            <Button type="primary" onClick={this.handleNew}>{messages('common.create')}</Button>{/*新建*/}
          </div>
        </div>
        <Table columns={columns}
               dataSource={data}
               pagination={pagination}
               loading={loading}
               onRow={record => ({onClick: () => this.handleRowClick(record)})}
               rowKey={record => record.id}
               bordered
               size="middle"/>

        <SlideFrame content={NewApplicationType}
                    title={isNew ? messages('finance-setting.key58'/*新建申请类型*/) : messages('finance-setting.key59'/*编辑申请类型*/)}
                    show={showSlideFrame}
                    onClose={()=>this.setState({showSlideFrame:false})}
                    afterClose={this.handleCloseSlide} params={nowApplicationType}/>
      </div>
    )
  }
}

ApplicationTypeManagement.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company
  }
}

export default connect(mapStateToProps)(ApplicationTypeManagement)


